<script setup>
import {onMounted, ref, watch } from "vue";

// const { weatherInfo }
const props = defineProps({
  // 这样解构丢失了响应性?
  data: {
    type: Object,
  },
});
// 预报天气数据
const resData = ref([]);
//转换数据格式 : 使用闭包和立即执行函数,避免重复声明变量和变量污染
const convertData = ((data) => {
  //0-6 ->'日'，'一'，'二'，'三'，'四'，'五'，'六'
  const week = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
  // 格式化日期
  return function (data) {
    const newData = data.map((item) => {
      return {
        /* YYYY-MM-DD -> MM-DD */
        week: week[item.week],
        date: item.date.slice(5),
        dayweather: item.dayweather,
        daypower: item.daypower,
      };
    });
    newData[0] = { ...newData[0], week: "今天" };
    newData[1] = { ...newData[1], week: "明天" };
    return newData;
  };
})(props.data);

watch(
  () => props.data,
  (newVal, oldVal) => {
    resData.value = convertData(newVal);
    renderChart(newVal);
  }
);

onMounted(() => {
  //这里仍然拿不到数据，因为子组件先于父组件挂载，并且获取数据是异步请求
  // console.log(props.weatherInfo, "weatherInfo in InfoChart.vue");
});

// 图表配置
const option = ref({});

const renderChart = (data) => {
  // 白天数据
  const dayData = data.map((item) => item.daytemp);
  // 夜间数据
  const nightData = data.map((item) => item.nighttemp);
  option.value = {
    grid: {
      top: "20",
      left: "12%",
      right: "12%",
      bottom: "0",
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      show: false,
    },
    yAxis: {
      type: "value",
      show: false,
      splitLine: {
        show: false,
      },
    },
    series: [
      {
        name: "Day Temperature",
        type: "line",
        data: dayData,
        label:{
          show: true,
          formatter: (params) => {
            return '白' + params.value + "°C";
          },
          color: "#fff",
        },
      },
      {
        name: "Night Temperature",
        type: "line",
        data: nightData,
        label:{
          show: true,
          /* 位置调整 */
          position:"bottom",
          formatter: (params) => {
            return '晚' +params.value + "°C";
          },
          color: "#fff",
        },
      },
    ],
  };
};
</script>

<template>
  <div class="bg-weather-second px-12 pt-10 mt-2 rounded">
    <div class="days flex gap-6">
      <div
        v-for="(item, index) in resData"
        class="flex flex-1 flex-col text-center gap-4"
      >
        <span>{{ item.week }}</span>
        <span>{{ item.date }}</span>
        <span>{{ item.dayweather }}</span>
        <span>风力 {{ item.daypower }}级</span>
      </div>
    </div>
    <div class="info-chart h-40 mt-10">
      <v-chart :option="option"></v-chart>
    </div>
  </div>
</template>
